/*
Copyright © 2021 NAME HERE <EMAIL ADDRESS>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd

import (
	"path/filepath"

	"gitee.com/extrame/fb-runner/ca"
	"gitee.com/extrame/fb-runner/connection"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
)

var clientConfig struct {
	Language   *string
	DeployBase *string
	Base       string
	Channel    *string
}

// clientCmd represents the client command
var clientCmd = &cobra.Command{
	Use:   "client",
	Short: "生成客户端配置文件",
	Long:  ``,
	Run: func(cmd *cobra.Command, args []string) {
		if *clientConfig.Channel == "" {
			logrus.Fatal("Channel配置为空")
		}
		if *clientConfig.Language == "" {
			logrus.Fatal("Language配置为空,请选择java或者golang")
		}
		logrus.Info("生成connection.yaml")
		//根据org获得原始生成的coonnect文件，替换

		var err error

		clientConfig.Base, err = filepath.Abs(clientConfig.Base)
		checkErr(err)

		var orgName = "org1"
		if len(args) > 0 {
			orgName = args[0]
		}
		if org, ok := cfg.Organizations[orgName]; ok {

			var admin = &ca.User{
				Name:       "admin",
				JustEnroll: true,
			}

			var appUser = &ca.User{
				Name: "appUser",
			}

			err = ca.CreateUser(clientConfig.Base, cfg.GetBase(), org, admin)

			if err == nil {

				err = ca.CreateUser(clientConfig.Base, cfg.GetBase(), org, appUser)

				if err == nil {
					logrus.Infoln("Generating CCP files for " + org.GetName())

					err = connection.Generate(*clientConfig.Channel, cfg.GetSource(), cfg.GetBase(), clientConfig.Base, *clientConfig.DeployBase, org, *clientConfig.Language, admin, appUser)

					if err != nil {
						err = errors.Wrap(err, "generate ccp for "+org.GetName()+" fail")
					}
				}
			}

		} else {
			err = errors.New("没有这个org：" + orgName)
		}
		cobra.CheckErr(err)
	},
}

func init() {
	rootCmd.AddCommand(clientCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// clientCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	clientConfig.Channel = clientCmd.Flags().StringP("channel", "C", "", "Channel名称")
	clientConfig.Language = clientCmd.Flags().StringP("language", "l", "java", "生成的语言")
	clientConfig.DeployBase = clientCmd.Flags().StringP("deploy_base", "d", "/code/config", "生成配置文件中的根路径")
	clientCmd.Flags().StringVarP(&clientConfig.Base, "base", "b", "./client_files", "配置文件暂存路径")
}
